/**
 * 新增订单抽屉组件
 * 基于截图参考实现的订单创建功能
 */

import React, { useState, useCallback, useEffect } from 'react';
import Drawer from './Drawer';
import type { Room } from '../../../types/room';

export interface OrderFormData {
  // 游客基本信息
  guestName: string;
  guestPhone: string;
  guestIdCard: string;

  // 住宿信息
  checkInDate: string;
  checkInTime: string;
  checkOutDate: string;
  checkOutTime: string;
  nights: number;

  // 房间信息
  selectedRoomId: string;
  roomType: string;

  // 价格信息
  roomPrice: number;
  totalAmount: number;

  // 其他信息
  guestCount: number;
  specialRequests: string;
}

export interface OrderDrawerProps {
  visible: boolean;
  onClose: () => void;
  onSubmit: (orderData: OrderFormData) => void;
  rooms: Room[];
  selectedRoomId?: string;
  selectedDate?: string;
  availableRooms?: Room[];
}

const OrderDrawer: React.FC<OrderDrawerProps> = ({
  visible,
  onClose,
  onSubmit,
  rooms,
  selectedRoomId,
  selectedDate,
  availableRooms = [],
}) => {
  const [formData, setFormData] = useState<OrderFormData>({
    guestName: '',
    guestPhone: '',
    guestIdCard: '',
    checkInDate: selectedDate || '',
    checkInTime: '15:00',
    checkOutDate: '',
    checkOutTime: '12:00',
    nights: 1,
    selectedRoomId: selectedRoomId || '',
    roomType: '',
    roomPrice: 0,
    totalAmount: 0,
    guestCount: 1,
    specialRequests: '',
  });

  const [errors, setErrors] = useState<
    Partial<Record<keyof OrderFormData, string>>
  >({});

  // 根据选中房间更新房型和价格
  useEffect(() => {
    if (formData.selectedRoomId) {
      const room = rooms.find(r => r.id === formData.selectedRoomId);
      if (room) {
        setFormData(prev => ({
          ...prev,
          roomType: room.roomType,
          roomPrice: room.price,
          totalAmount: room.price * prev.nights,
        }));
      }
    }
  }, [formData.selectedRoomId, rooms]);

  // 计算总金额
  useEffect(() => {
    setFormData(prev => ({
      ...prev,
      totalAmount: prev.roomPrice * prev.nights,
    }));
  }, [formData.roomPrice, formData.nights]);

  // 计算入住天数
  useEffect(() => {
    if (formData.checkInDate && formData.checkOutDate) {
      const checkIn = new Date(formData.checkInDate);
      const checkOut = new Date(formData.checkOutDate);
      const diffTime = checkOut.getTime() - checkIn.getTime();
      const nights = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      if (nights > 0) {
        setFormData(prev => ({
          ...prev,
          nights,
        }));
      }
    }
  }, [formData.checkInDate, formData.checkOutDate]);

  // 表单字段更新
  const updateField = useCallback(
    <K extends keyof OrderFormData>(field: K, value: OrderFormData[K]) => {
      setFormData(prev => ({
        ...prev,
        [field]: value,
      }));

      // 清除对应字段的错误
      if (errors[field]) {
        setErrors(prev => {
          const newErrors = { ...prev };
          delete newErrors[field];
          return newErrors;
        });
      }
    },
    [errors]
  );

  // 表单验证
  const validateForm = useCallback((): boolean => {
    const newErrors: Partial<Record<keyof OrderFormData, string>> = {};

    if (!formData.guestName.trim()) {
      newErrors.guestName = '请输入客人姓名';
    }

    if (!formData.guestPhone.trim()) {
      newErrors.guestPhone = '请输入手机号';
    } else if (!/^1[3-9]\d{9}$/.test(formData.guestPhone)) {
      newErrors.guestPhone = '请输入正确的手机号';
    }

    if (!formData.checkInDate) {
      newErrors.checkInDate = '请选择入住日期';
    }

    if (!formData.checkOutDate) {
      newErrors.checkOutDate = '请选择退房日期';
    }

    if (formData.checkInDate && formData.checkOutDate) {
      const checkIn = new Date(formData.checkInDate);
      const checkOut = new Date(formData.checkOutDate);
      if (checkOut <= checkIn) {
        newErrors.checkOutDate = '退房日期必须晚于入住日期';
      }
    }

    if (!formData.selectedRoomId) {
      newErrors.selectedRoomId = '请选择房间';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formData]);

  // 提交表单
  const handleSubmit = useCallback(() => {
    if (validateForm()) {
      onSubmit(formData);
      onClose();

      // 重置表单
      setFormData({
        guestName: '',
        guestPhone: '',
        guestIdCard: '',
        checkInDate: selectedDate || '',
        checkInTime: '15:00',
        checkOutDate: '',
        checkOutTime: '12:00',
        nights: 1,
        selectedRoomId: selectedRoomId || '',
        roomType: '',
        roomPrice: 0,
        totalAmount: 0,
        guestCount: 1,
        specialRequests: '',
      });
      setErrors({});
    }
  }, [formData, validateForm, onSubmit, onClose, selectedDate, selectedRoomId]);

  // 获取可用房间列表
  const getAvailableRooms = useCallback(() => {
    if (availableRooms.length > 0) {
      return availableRooms;
    }
    return rooms.filter(() => {
      // 这里可以添加房间可用性检查逻辑
      return true;
    });
  }, [rooms, availableRooms]);

  return (
    <Drawer visible={visible} title='新增订单' width={450} onClose={onClose}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        {/* 游客基本信息 */}
        <div>
          <h4
            style={{
              margin: '0 0 16px 0',
              fontSize: '14px',
              fontWeight: 600,
              color: '#262626',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
            }}
          >
            <span style={{ color: '#52c41a' }}>●</span>
            游客基本信息
          </h4>

          <div
            style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
          >
            <div>
              <label
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: '#262626',
                  fontWeight: 500,
                }}
              >
                姓名 <span style={{ color: '#ff4d4f' }}>*</span>
              </label>
              <input
                type='text'
                value={formData.guestName}
                onChange={e => updateField('guestName', e.target.value)}
                placeholder='请输入姓名'
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: errors.guestName
                    ? '1px solid #ff4d4f'
                    : '1px solid #d9d9d9',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  boxSizing: 'border-box',
                }}
                onFocus={e => {
                  e.target.style.borderColor = '#1890ff';
                  e.target.style.boxShadow =
                    '0 0 0 2px rgba(24, 144, 255, 0.2)';
                }}
                onBlur={e => {
                  e.target.style.borderColor = errors.guestName
                    ? '#ff4d4f'
                    : '#d9d9d9';
                  e.target.style.boxShadow = 'none';
                }}
              />
              {errors.guestName && (
                <div
                  style={{
                    color: '#ff4d4f',
                    fontSize: '12px',
                    marginTop: '4px',
                  }}
                >
                  {errors.guestName}
                </div>
              )}
            </div>

            <div>
              <label
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: '#262626',
                  fontWeight: 500,
                }}
              >
                手机号 <span style={{ color: '#ff4d4f' }}>*</span>
              </label>
              <input
                type='tel'
                value={formData.guestPhone}
                onChange={e => updateField('guestPhone', e.target.value)}
                placeholder='请输入手机号'
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: errors.guestPhone
                    ? '1px solid #ff4d4f'
                    : '1px solid #d9d9d9',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  boxSizing: 'border-box',
                }}
                onFocus={e => {
                  e.target.style.borderColor = '#1890ff';
                  e.target.style.boxShadow =
                    '0 0 0 2px rgba(24, 144, 255, 0.2)';
                }}
                onBlur={e => {
                  e.target.style.borderColor = errors.guestPhone
                    ? '#ff4d4f'
                    : '#d9d9d9';
                  e.target.style.boxShadow = 'none';
                }}
              />
              {errors.guestPhone && (
                <div
                  style={{
                    color: '#ff4d4f',
                    fontSize: '12px',
                    marginTop: '4px',
                  }}
                >
                  {errors.guestPhone}
                </div>
              )}
            </div>

            <div>
              <label
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: '#262626',
                  fontWeight: 500,
                }}
              >
                身份证号
              </label>
              <input
                type='text'
                value={formData.guestIdCard}
                onChange={e => updateField('guestIdCard', e.target.value)}
                placeholder='请输入身份证号'
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  boxSizing: 'border-box',
                }}
                onFocus={e => {
                  e.target.style.borderColor = '#1890ff';
                  e.target.style.boxShadow =
                    '0 0 0 2px rgba(24, 144, 255, 0.2)';
                }}
                onBlur={e => {
                  e.target.style.borderColor = '#d9d9d9';
                  e.target.style.boxShadow = 'none';
                }}
              />
            </div>
          </div>
        </div>

        {/* 住宿信息 */}
        <div>
          <h4
            style={{
              margin: '0 0 16px 0',
              fontSize: '14px',
              fontWeight: 600,
              color: '#262626',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
            }}
          >
            <span style={{ color: '#1890ff' }}>●</span>
            住宿信息
          </h4>

          <div
            style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
          >
            <div style={{ display: 'flex', gap: '12px' }}>
              <div style={{ flex: 1 }}>
                <label
                  style={{
                    display: 'block',
                    marginBottom: '8px',
                    fontSize: '14px',
                    color: '#262626',
                    fontWeight: 500,
                  }}
                >
                  入住日期 <span style={{ color: '#ff4d4f' }}>*</span>
                </label>
                <input
                  type='date'
                  value={formData.checkInDate}
                  onChange={e => updateField('checkInDate', e.target.value)}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: errors.checkInDate
                      ? '1px solid #ff4d4f'
                      : '1px solid #d9d9d9',
                    borderRadius: '6px',
                    fontSize: '14px',
                    outline: 'none',
                    transition: 'border-color 0.2s',
                    boxSizing: 'border-box',
                  }}
                />
                {errors.checkInDate && (
                  <div
                    style={{
                      color: '#ff4d4f',
                      fontSize: '12px',
                      marginTop: '4px',
                    }}
                  >
                    {errors.checkInDate}
                  </div>
                )}
              </div>

              <div style={{ width: '80px' }}>
                <label
                  style={{
                    display: 'block',
                    marginBottom: '8px',
                    fontSize: '14px',
                    color: '#262626',
                    fontWeight: 500,
                  }}
                >
                  时间
                </label>
                <input
                  type='time'
                  value={formData.checkInTime}
                  onChange={e => updateField('checkInTime', e.target.value)}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '6px',
                    fontSize: '14px',
                    outline: 'none',
                    transition: 'border-color 0.2s',
                    boxSizing: 'border-box',
                  }}
                />
              </div>
            </div>

            <div style={{ display: 'flex', gap: '12px' }}>
              <div style={{ flex: 1 }}>
                <label
                  style={{
                    display: 'block',
                    marginBottom: '8px',
                    fontSize: '14px',
                    color: '#262626',
                    fontWeight: 500,
                  }}
                >
                  退房日期 <span style={{ color: '#ff4d4f' }}>*</span>
                </label>
                <input
                  type='date'
                  value={formData.checkOutDate}
                  onChange={e => updateField('checkOutDate', e.target.value)}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: errors.checkOutDate
                      ? '1px solid #ff4d4f'
                      : '1px solid #d9d9d9',
                    borderRadius: '6px',
                    fontSize: '14px',
                    outline: 'none',
                    transition: 'border-color 0.2s',
                    boxSizing: 'border-box',
                  }}
                />
                {errors.checkOutDate && (
                  <div
                    style={{
                      color: '#ff4d4f',
                      fontSize: '12px',
                      marginTop: '4px',
                    }}
                  >
                    {errors.checkOutDate}
                  </div>
                )}
              </div>

              <div style={{ width: '80px' }}>
                <label
                  style={{
                    display: 'block',
                    marginBottom: '8px',
                    fontSize: '14px',
                    color: '#262626',
                    fontWeight: 500,
                  }}
                >
                  时间
                </label>
                <input
                  type='time'
                  value={formData.checkOutTime}
                  onChange={e => updateField('checkOutTime', e.target.value)}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '6px',
                    fontSize: '14px',
                    outline: 'none',
                    transition: 'border-color 0.2s',
                    boxSizing: 'border-box',
                  }}
                />
              </div>
            </div>

            <div>
              <label
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: '#262626',
                  fontWeight: 500,
                }}
              >
                选择房间 <span style={{ color: '#ff4d4f' }}>*</span>
              </label>
              <select
                value={formData.selectedRoomId}
                onChange={e => updateField('selectedRoomId', e.target.value)}
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: errors.selectedRoomId
                    ? '1px solid #ff4d4f'
                    : '1px solid #d9d9d9',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  boxSizing: 'border-box',
                  backgroundColor: '#fff',
                }}
              >
                <option value=''>请选择房间</option>
                {getAvailableRooms().map(room => (
                  <option key={room.id} value={room.id}>
                    {room.roomNumber} - {room.roomType} - ¥{room.price}/晚
                  </option>
                ))}
              </select>
              {errors.selectedRoomId && (
                <div
                  style={{
                    color: '#ff4d4f',
                    fontSize: '12px',
                    marginTop: '4px',
                  }}
                >
                  {errors.selectedRoomId}
                </div>
              )}
            </div>

            <div>
              <label
                style={{
                  display: 'block',
                  marginBottom: '8px',
                  fontSize: '14px',
                  color: '#262626',
                  fontWeight: 500,
                }}
              >
                入住人数
              </label>
              <input
                type='number'
                min='1'
                max='10'
                value={formData.guestCount}
                onChange={e =>
                  updateField('guestCount', parseInt(e.target.value) || 1)
                }
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  boxSizing: 'border-box',
                }}
              />
            </div>
          </div>
        </div>

        {/* 价格信息 */}
        <div>
          <h4
            style={{
              margin: '0 0 16px 0',
              fontSize: '14px',
              fontWeight: 600,
              color: '#262626',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
            }}
          >
            <span style={{ color: '#52c41a' }}>●</span>
            费用信息
          </h4>

          <div
            style={{
              backgroundColor: '#f6ffed',
              border: '1px solid #b7eb8f',
              borderRadius: '6px',
              padding: '16px',
            }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                marginBottom: '8px',
              }}
            >
              <span style={{ color: '#595959' }}>
                房间: {formData.nights} 晚
              </span>
              <span style={{ color: '#595959' }}>¥{formData.roomPrice}/晚</span>
            </div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <span
                style={{ fontSize: '16px', fontWeight: 600, color: '#262626' }}
              >
                分摊合计:
              </span>
              <span
                style={{ fontSize: '20px', fontWeight: 600, color: '#52c41a' }}
              >
                ¥{formData.totalAmount.toFixed(2)}
              </span>
            </div>
          </div>
        </div>

        {/* 特殊要求 */}
        <div>
          <label
            style={{
              display: 'block',
              marginBottom: '8px',
              fontSize: '14px',
              color: '#262626',
              fontWeight: 500,
            }}
          >
            特殊要求
          </label>
          <textarea
            value={formData.specialRequests}
            onChange={e => updateField('specialRequests', e.target.value)}
            placeholder='请输入特殊要求'
            rows={3}
            style={{
              width: '100%',
              padding: '8px 12px',
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              fontSize: '14px',
              outline: 'none',
              transition: 'border-color 0.2s',
              boxSizing: 'border-box',
              resize: 'vertical',
            }}
            onFocus={e => {
              e.target.style.borderColor = '#1890ff';
              e.target.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
            }}
            onBlur={e => {
              e.target.style.borderColor = '#d9d9d9';
              e.target.style.boxShadow = 'none';
            }}
          />
        </div>

        {/* 操作按钮 */}
        <div
          style={{
            display: 'flex',
            gap: '12px',
            paddingTop: '20px',
            borderTop: '1px solid #f0f0f0',
            marginTop: '20px',
          }}
        >
          <button
            onClick={onClose}
            style={{
              flex: 1,
              padding: '10px 16px',
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              fontSize: '14px',
              fontWeight: 500,
              color: '#595959',
              backgroundColor: '#fff',
              cursor: 'pointer',
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.borderColor = '#40a9ff';
              e.currentTarget.style.color = '#40a9ff';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.borderColor = '#d9d9d9';
              e.currentTarget.style.color = '#595959';
            }}
          >
            取消
          </button>

          <button
            onClick={handleSubmit}
            style={{
              flex: 2,
              padding: '10px 16px',
              border: 'none',
              borderRadius: '6px',
              fontSize: '14px',
              fontWeight: 500,
              color: '#fff',
              backgroundColor: '#1890ff',
              cursor: 'pointer',
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.backgroundColor = '#40a9ff';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.backgroundColor = '#1890ff';
            }}
          >
            确认创建订单
          </button>
        </div>
      </div>
    </Drawer>
  );
};

export default OrderDrawer;
